package com.sunyur.tailor.channel.service.inner.materiel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.sunyur.tailor.channel.common.inner.base.SunyurListResult;
import com.sunyur.tailor.channel.common.inner.base.SunyurResult;
import com.sunyur.tailor.channel.common.inner.util.SunyurClientUtil;
import com.sunyur.tailor.channel.common.inner.util.SunyurResultUtil;
import com.sunyur.tailor.channel.common.middle.base.ChannelListResult;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelListResultUtil;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.materiel.model.*;
import com.sunyur.tailor.channel.service.inner.materiel.param.*;
import com.sunyur.tailor.channel.service.inner.materiel.service.SunyurMaterielService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SunyurMaterielServiceImpl
 * @Description 物料接口
 * @Author hao.tian
 * @Date 2021/5/20
 * @Version v1.0
 */
@Service("sunyurMaterielService")
public class SunyurMaterielServiceImpl implements SunyurMaterielService {

    private static final Logger LOGGER_INFO = LoggerFactory.getLogger(SunyurMaterielServiceImpl.class);
    private static final Logger LOGGER_ERROR = LoggerFactory.getLogger(SunyurMaterielServiceImpl.class);

    /**
     * 请求商越Client
     */
    @Autowired
    private SunyurClientUtil sunyurClient;

    /**
     * 批量添加物料接口 链接
     */
    @Value("${sunyur.api.batchAdditionMateriel}")
    private String batchAdditionMateriel;

    /**
     * 批量获取物料接口 链接
     */
    @Value("${sunyur.api.listMateriel}")
    private String listMateriel;

    /**
     * 批量获取物料通过修改时间接口 链接
     */
    @Value("${sunyur.api.listPagingByModifyTime}")
    private String listPagingByModifyTime;

    /**
     * 商品批量替换物料(API_WEB非标准接口)（最大支持50条数据一次请求） 链接
     */
    @Value("${sunyur.api.replaceItemMaterial}")
    private String replaceItemMaterial;

    /**
     * @Author pengbing
     * @Description 批量添加物料
     * @WIKI 10-批量添加物料【已上线】   http://doc.sunyur.com/pages/viewpage.action?pageId=61309118
     * @Date 15:15 2021/7/9
     * @Param [createCategoryParamList]
     * @return com.sunyur.tailor.channel.common.middle.base.ChannelResult
     **/
    @Override
    public ChannelResult batchAdditionMateriel(List<BatchAdditionMaterielParam> batchAdditionMaterielParamList) throws Exception {
        LOGGER_INFO.info("SunyurCategoryServiceImpl batchAdditionMateriel param is {}", JSON.toJSONString(batchAdditionMaterielParamList));
        if (ObjectUtils.isEmpty(batchAdditionMaterielParamList)) {
            return ChannelResultUtil.error(MiddleResultEnum.PARAM_NULL.getCode(), "SunyurCategoryServiceImpl batchAdditionMateriel param is null");
        }
        // 参数按长度分割
        List<List<BatchAdditionMaterielParam>> additionMaterielList = Lists.partition(batchAdditionMaterielParamList, 1);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        for (List<BatchAdditionMaterielParam> batchAdditionMaterielParams : additionMaterielList) {
            // 调用主线接口
            SunyurResult sunyurResult = sunyurClient.execPost(batchAdditionMateriel, JSON.toJSONString(batchAdditionMaterielParams), null);
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                LOGGER_ERROR.error("batchAdditionMateriel loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(batchAdditionMaterielParams), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
           return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(null);
    }

    /**
     * @Author pengbing
     * @Description 批量获取物料
     * @WIKI 12-批量获取物料【已上线】   http://doc.sunyur.com/pages/viewpage.action?pageId=66388163
     * @Date 15:15 2021/7/9
     * @Param [createCategoryParamList]
     * @return com.sunyur.tailor.channel.common.middle.base.ChannelResult
     **/
    @Override
    public ChannelResult<List<ListMaterielModel>> listMateriel(ListMaterielParam listMaterielParam) throws Exception {
        LOGGER_INFO.info("SunyurCategoryServiceImpl listMateriel param is {}", JSON.toJSONString(listMaterielParam));
        if (ObjectUtils.isEmpty(listMaterielParam)) {
            return ChannelResultUtil.error(MiddleResultEnum.PARAM_NULL.getCode(), "SunyurCategoryServiceImpl listMateriel param is null");
        }
        List<ListMaterielModel> resultList=new ArrayList<>();
        List<List<String>> materielList=Lists.partition(listMaterielParam.getMaterielCodes(),20);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        ListMaterielParam listMaterielParamClient = new ListMaterielParam();
        TypeReference<SunyurResult<List<ListMaterielModel>>> typeReference = new TypeReference<SunyurResult<List<ListMaterielModel>>>() {
        };
        for (List<String> strings : materielList) {
            listMaterielParamClient.setMaterielCodes(strings);
            // 调用主线接口
            SunyurResult<List<ListMaterielModel>> sunyurResult = sunyurClient.execPost(listMateriel, JSON.toJSONString(listMaterielParamClient), typeReference);
            if (SunyurResultUtil.isSuccess(sunyurResult)) {
                resultList.addAll(sunyurResult.getContent());
            } else {
                LOGGER_ERROR.error("listMateriel loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(listMaterielParamClient), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(resultList);
    }

    /**
     * @Author pengbing
     * @Description 批量获取物料通过修改时间接口
     * @WIKI 25-批量获取物料   http://doc.sunyur.com/pages/viewpage.action?pageId=117014799
     * @Date 15:15 2021/7/9
     * @Param [createCategoryParamList]
     * @return com.sunyur.tailor.channel.common.middle.base.ChannelResult
     **/
    @Override
    public ChannelListResult<ListPagingByModifyTimeModel> listPagingByModifyTime(ListPagingByModifyTimeParam listPagingByModifyTimeParam) throws Exception {
        LOGGER_INFO.info("SunyurCategoryServiceImpl listPagingByModifyTime param is {}", JSON.toJSONString(listPagingByModifyTimeParam));
        if (ObjectUtils.isEmpty(listPagingByModifyTimeParam)) {
            return ChannelListResultUtil.error(MiddleResultEnum.PARAM_NULL.getCode(), "SunyurCategoryServiceImpl listPagingByModifyTime param is null");
        }
        if (ObjectUtils.isEmpty(listPagingByModifyTimeParam.getPage())) {
            listPagingByModifyTimeParam.setPage(0);
        }
        if (listPagingByModifyTimeParam.getPageSize() > 100 || ObjectUtils.isEmpty(listPagingByModifyTimeParam.getPageSize())) {
            listPagingByModifyTimeParam.setPageSize(100);
        }
        // 调用主线接口
        TypeReference<SunyurListResult<ListPagingByModifyTimeModel>> typeReference = new TypeReference<SunyurListResult<ListPagingByModifyTimeModel>>() {
        };
        SunyurListResult<ListPagingByModifyTimeModel> sunyurListResult = sunyurClient.execListPost(listPagingByModifyTime, JSON.toJSONString(listPagingByModifyTimeParam), typeReference);
        // 主线报错
        if (!SunyurResultUtil.isSuccess(sunyurListResult)) {
            return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurListResult.getErrorMessage());
        }
        // 判断是否存在下一页
        if (!SunyurResultUtil.isNextPage(sunyurListResult)) {
            return ChannelListResultUtil.success(sunyurListResult.getContent());
        }

        // 返回结果集
        List<ListPagingByModifyTimeModel> resultList = Lists.newArrayList();
        // 将第一次查询的结果收集
        resultList.addAll(sunyurListResult.getContent());
        // 循环查询剩余数据
        for (int i = listPagingByModifyTimeParam.getPage() + 1; i <= sunyurListResult.getTotalPage(); i++) {
            listPagingByModifyTimeParam.setPage(i);
            // 调用主线接口
            SunyurListResult<ListPagingByModifyTimeModel> sunyurPageResult = sunyurClient.execListPost(listPagingByModifyTime, JSON.toJSONString(listPagingByModifyTimeParam), typeReference);
            // 某次调用主线返回错误（小概率，可能网络等原因，此时结果集数据不完整，本次查询失败）
            if (!SunyurResultUtil.isSuccess(sunyurPageResult)) {
                LOGGER_ERROR.error("listPagingByModifyTime loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(listPagingByModifyTimeParam), JSON.toJSONString(sunyurPageResult));
                return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurPageResult.getErrorMessage());
            }
            resultList.addAll(sunyurPageResult.getContent());
        }
        return ChannelListResultUtil.success(resultList);
    }


    @Override
    public ChannelResult batchReplaceItemMaterial(List<ReplaceItemMaterialModel> materielList) throws Exception {
        LOGGER_INFO.info("SunyurCategoryServiceImpl batchReplaceItemMaterial param is {}", JSON.toJSONString(materielList));
        if (ObjectUtils.isEmpty(materielList)) {
            return ChannelResultUtil.error(MiddleResultEnum.PARAM_NULL.getCode(), "SunyurCategoryServiceImpl batchReplaceItemMaterial param is null");
        }
        // 参数按长度分割
        List<List<ReplaceItemMaterialModel>> additionMaterielList = Lists.partition(materielList, 1);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        for (List<ReplaceItemMaterialModel> batchAdditionMaterielParams : additionMaterielList) {
            // 调用主线接口
            SunyurResult sunyurResult = sunyurClient.execPost(replaceItemMaterial, JSON.toJSONString(batchAdditionMaterielParams), null);
            if (!sunyurResult.getCode().equals("00000")) {
                LOGGER_ERROR.error("batchReplaceItemMaterial loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(batchAdditionMaterielParams), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(true);
    }
}
